﻿using System;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Volo.Abp.Domain.Repositories.EntityFrameworkCore;
using Volo.Abp.EntityFrameworkCore;
using AdminFrame.Domain.Parameters;
using System.Collections.Generic;
using System.Linq.Dynamic.Core;

namespace AdminFrame.EntityFrameworkCore.Repositories
{
    public class ParameterRepository : EfCoreRepository<AdminFrameDbContext, Parameter, Guid>, IParameterRepository
    {
        public ParameterRepository(IDbContextProvider<AdminFrameDbContext> dbContextProvider)
            : base(dbContextProvider)
        {
        }

        public async Task<Parameter> FindByCodeAsync(string code)
        {
            return await DbSet.FirstOrDefaultAsync(p => p.Code == code);
        }

        public async Task<bool> CodeExistsAsync(string code, Guid? ignoredId = null)
        {
            var query = DbSet.Where(p => p.Code == code);

            if (ignoredId.HasValue)
            {
                query = query.Where(p => p.Id != ignoredId.Value);
            }

            return await query.AnyAsync();
        }

        public async Task<List<Parameter>> GetListAsync(
            string filter = null,
            int maxResultCount = int.MaxValue,
            int skipCount = 0,
            string sorting = null)
        {
            var query = DbSet.AsQueryable();

            // 应用过滤条件
            if (!string.IsNullOrWhiteSpace(filter))
            {
                query = query.Where(p =>
                    p.Name.Contains(filter) ||
                    p.Code.Contains(filter) ||
                    p.Description.Contains(filter));
            }

            // 应用排序
            if (!string.IsNullOrWhiteSpace(sorting))
            {
                query = query.OrderBy(sorting);
            }
            else
            {
                query = query.OrderBy(p => p.Name);
            }

            // 应用分页
            query = query.Skip(skipCount).Take(maxResultCount);

            return await query.ToListAsync();
        }
    }
}